package com.hm.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hm.gateway.config.AuthProperties;
import com.hm.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    // 这个类new出来，是因为没有使用@Component注解或其他配置类也没有@Bean来进行自动注入，所以需要手动new出来
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 先获取Request对象
        ServerHttpRequest request = exchange.getRequest();

        // 2. 判断request对象的请求路径是否需要拦截
        if (isExlude(request.getPath().toString())) {
            return chain.filter(exchange);
        }

        // 3. 获取请求头中的Token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollectionUtils.isEmpty(headers)) {
            token = headers.get(0);
        }

        // 4. 校验并解析Token
        Long userId = null;
        try {
             userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        // 5. 解析成功，将用户信息传递到微服务
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate()
                .request(b -> b.header("user-info", userInfo))
                .build();

        return chain.filter(ex);
    }

    private boolean isExlude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (excludePath.matches(path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
